#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("TCP客户端");
    connect(&m_timer,&QTimer::timeout,this,&Widget::tryRead);
    m_timer.setInterval(100);
}

Widget::~Widget()
{
    delete ui;
}

void   Widget::onStateChanged(QAbstractSocket::SocketState state)
{
    //枚举类型转为字符串、方便观测
     QString  strState = QMetaEnum::fromType
             <QAbstractSocket::SocketState>().valueToKey( state );

    QString str = QString("状态: %1").arg(strState);
    ui->messageShoxEdit->appendPlainText( str );
}


void Widget::tryRead()
{

    //如果已经不是连接状态，则退出循环
    if(m_tcpsocket.state() !=  QTcpSocket::ConnectedState)
    {
        onStateChanged(m_tcpsocket.state());
        return;
    }

    //阻塞等待是否有数据可以读取,可以设置超时时间
    //超时返回false，继续向下运行
    if(m_tcpsocket.waitForReadyRead(10))
    {
        //有数据可以读
        QByteArray  data = m_tcpsocket.readAll();
        QString str = QString("收到数据: %1").arg(QString(data));
        ui->messageShoxEdit->appendPlainText(str);
    }

}

void Widget::on_btnConnect_clicked()
{
    if(!m_connected)
    {
        //获取IP与端口
        QString ip= ui->lineEditIP->text();
        uint  port = ui->lineEditPort->text().toUInt();
            //连接到TCP服务器
        m_tcpsocket.connectToHost(ip,port);

        //使用阻塞函数判断是否连接成功,设置超时时间1s
        bool  bConn= m_tcpsocket.waitForConnected(1000);
        if(bConn)
        {
            ui->messageShoxEdit->appendPlainText("连接服务器成功！");
            ui->btnConnect->setText("断开");
            m_connected = true;
            m_timer.start();
        }else{
           QString strError=  m_tcpsocket.errorString();
           QString str = QString("错误: %1").arg(strError);
           ui->messageShoxEdit->appendPlainText( str );
        }
    }
    else
    {
        //断开与服务器的连接
        m_tcpsocket.disconnectFromHost();
        //判断一下状态，可以省略
        if((m_tcpsocket.state() ==  QTcpSocket::UnconnectedState)
            || m_tcpsocket.waitForDisconnected(10))
        {
            ui->messageShoxEdit->appendPlainText("连接被断开！");
            ui->btnConnect->setText("连接");
            m_connected = false;
        }
        m_timer.stop();
    }
}

void Widget::on_btnSend_clicked()
{
    QString  msg = ui->messageEdit->text();
    //给服务端发送数据
    m_tcpsocket.write(msg.toUtf8());
    if(m_tcpsocket.waitForBytesWritten(10))
    {
        ui->messageEdit->setText("");
    }
}
